package com.example.springcloudgateway.encrypt;


import com.example.springcloudgateway.util.CharsetUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 * @author yijie
 */
public class Base64 {

    //final private static Logger logger = LoggerFactory.getLogger(Base64.class);

    /**
     * encode string (utf-8)
     *
     * @param data    original string
     * @return base64 string
     */
    public static String encode(String data) {
        return encode(data, null);
    }

    /**
     * encode string
     *
     * @param data    original string
     * @param charset charset (can be null)
     * @return base64 string
     */
    public static String encode(String data, String charset) {
        if (StringUtils.isEmpty(data)) {
            return "";
        }

        String c = CharsetUtil.getCharset(charset);
        String result = "";
        try {
            result = org.apache.commons.codec.binary.Base64.encodeBase64String(data.getBytes(c));
        } catch (UnsupportedEncodingException e) {
            //logger.error(e.getMessage());
        }
        return result;
    }

    /**
     * decode base64 string (utf-8)
     *
     * @param data    base64 string
     * @return original string
     */
    public static String decode(String data) {
        return decode(data, null);
    }

    /**
     * decode base64 string
     *
     * @param data    base64 string
     * @param charset charset (can be null)
     * @return original string
     */
    public static String decode(String data, String charset) {
        if (StringUtils.isEmpty(data)) {
            return "";
        }

        String c = CharsetUtil.getCharset(charset);
        String result = "";
        try {
            byte[] b = org.apache.commons.codec.binary.Base64.decodeBase64(data.getBytes(c));
            result = new String(b, c).trim();
        } catch (UnsupportedEncodingException e) {
            //logger.error(e.getMessage());
        }

        return result;
    }

}
